package com.ly.auto.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.utils.StringUtils;
import com.ly.auto.dto.UserInfoDTO;
import com.ly.auto.entity.User;
import com.ly.auto.param.UserParam;
import com.ly.auto.service.RedisService;
import com.ly.auto.service.UserService;
import com.ly.core.enums.BaseStatus;
import com.ly.core.send.SmsTool;
import com.ly.core.utils.CodeUtil;
import com.ly.core.utils.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(description = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    /***
     * 注入redis模版
     */
    @Autowired
    private RedisService redisService;
    private  String tokenId="TOKEN-USER-";

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @ApiOperation(value = "用户注册")
    @PutMapping
    public ResponseData install(@RequestBody UserParam userParam){
        User user = new User();
        user.setUserName(userParam.getUserName());
        user.setPhone(userParam.getPhone());
        user.setRole(userParam.getRole());
        user.setPassword(bCryptPasswordEncoder.encode(userParam.getPassword()));
//        BeanUtils.copyProperties(userParam,user);
        user.setStatus(BaseStatus.ENABLE.getValue());
        userService.save(user);
        return ResponseData.success("新增成功！");
    }


    @ApiOperation(value = "获取验证码")
    @GetMapping("/phone/{phone}")
    public ResponseData getPhoneCode(@PathVariable String phone) throws ClientException {
        Map<String,Object> map = new HashMap<>();
        // 调用工具栏中生成验证码方法（指定长度的随机数）
        String code = CodeUtil.generateVerifyCode(6);
        //填充验证码
        String TemplateParam = "{\"code\":\""+code+"\"}";
        SendSmsResponse response = SmsTool.sendSms(phone,TemplateParam);//传入手机号码及短信模板中的验证码占位符

        map.put("verifyCode",code);
        map.put("phone",phone);
//        request.getSession().setAttribute("CodePhone",map);
        if( response.getCode().equals("OK")) {
            map.put("isOk","OK");
            //验证码绑定手机号并存储到redis
            redisService.set(tokenId+phone,code);
            redisService.expire(tokenId+phone,620);//调用reids工具类中存储方法设置超时时间
        }
        return ResponseData.success(map);
    }

    /**
     * 注册验证
     * @ResponseBody 返回json数据
     * @RequestMapping 拦截请求，指定请求类型：POST
     * @RequestBody 接受前台传入的json数据 接受类型为Map
     * @throws ClientException 抛出异常
     */
    @ApiOperation(value = "短信注册")
    @PostMapping("/validateNum")
    public ResponseData validateNum(@RequestBody Map<String,Object> requestMap) throws ClientException {

        Map<String,Object> map = new HashMap<>();
        String phone = requestMap.get("phone").toString();//获取注册手机号码
        String verifyCode = requestMap.get("verifyCode").toString();//获取手机验证码

        //首先比对验证码是否失效
        String redisauthcode= redisService.get(tokenId+phone); //传入tonkenId返回redis中的value
        if(StringUtils.isEmpty(redisauthcode)){
            //如果未取到则过期验证码已失效
            map.put("ruselt",404);
        }else  if(!"".equals(redisauthcode)&&!verifyCode.equals(redisauthcode)){
            //验证码错误
            map.put("ruselt",500);
        }else{
            User user = new User();
            user.setPhone(phone);
            user.setUserName(requestMap.get("userName").toString());
            user.setPassword(requestMap.get("passWord").toString());
            user.setStatus(BaseStatus.ENABLE.getValue());
            userService.save(user);
            //用户注册成功
            map.put("ruselt",200);
        }
        return ResponseData.success(map);
    }

    @ApiOperation(value = "用户密码修改")
    @PostMapping
    public ResponseData update(){
        return ResponseData.success("");
    }
}
